package com.trg.flex.dp
{
	import com.trg.flex.Callback;
	import com.trg.flex.FrameworkConfig;
	import com.trg.flex.IEntityDelegate;
	import com.trg.flex.search.Search;
	import com.trg.flex.search.SearchResult;
	
	import flash.events.Event;
	
	import mx.collections.Sort;
	import mx.controls.Alert;
	import mx.events.PropertyChangeEvent;
	import mx.rpc.Fault;
	[Event(name="refreshResults")]
	[DefaultProperty("search")]
	public class CustomDataProvider extends DataProvider
	{
		public static var entityDelegate:IEntityDelegate = FrameworkConfig.entityDelegate;
		
		public function CustomDataProvider(search:Search=null)
		{
			super();
			_search = search;
		}
		
		protected var _search:Search;
		protected var _totalResults:int;
		
		public function set search(value:Search):void {
			if (_search != null) {
				_search.removeEventListener(PropertyChangeEvent.PROPERTY_CHANGE, searchChangeListener);
			}			
			_search = value;
			if (_search != null) {
				_search.addEventListener(PropertyChangeEvent.PROPERTY_CHANGE, searchChangeListener);
				sort = _search.sort;
				page = _search.page;
				resultsPerPage = _search.maxResults;
			}
		}
		public function get search():Search {
			return _search;
		}
		
		override public function get totalResults():int {
			return _totalResults;
		}
		
		override protected function refreshData():Boolean {
			dispatchEvent(new Event("refreshResults"));
			return false;
		}
		
		public function setResult(list:Array, totalLength:int) {
			data.source = list;
			_totalResults = totalLength;
			refreshComplete();
			dispatchEvent(new Event(TOTAL_RESULTS_CHANGED));
		}
		
		public const searchCallback:Callback = new Callback(searchSuccess, searchFailed);
		
		protected function searchSuccess(result:SearchResult):void {
			setResult(result.result.source, result.totalCount);
		}
		
		protected function searchFailed(fault:Fault):void {
			setResult(null, 0);
			Alert.show(fault.toString());
		}
		
		protected var processingChange:Boolean;
		protected function searchChangeListener(event:PropertyChangeEvent):void {
			processingChange = true;
			switch (event.property) {
				case "sort": sort = _search.sort; break;
				case "page": page = _search.page; break;
				case "maxResults": resultsPerPage = _search.maxResults; break;
			}
			processingChange = false;
		}
		
		override public function set sort(value:Sort):void {
			super.sort = value;
			if (!processingChange && _search != null) _search.sort = _sort;
		}
		
		override public function set page(value:int):void {
			super.page = value;
			if (!processingChange && _search != null) _search.page = _page;
		}
		
		override public function set resultsPerPage(value:int):void {
			super.resultsPerPage = value;
			if (!processingChange && _search != null) _search.maxResults = _resultsPerPage;
		}
	}
}